package learn_concurrent._7;

import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T1 {
	static final Logger logger = LoggerFactory.getLogger(T1.class);

	public static void main(String[] args) throws InterruptedException {
		Chopstick chopstick1 = new Chopstick("1");
		Chopstick chopstick2 = new Chopstick("2");
		Chopstick chopstick3 = new Chopstick("3");
		Chopstick chopstick4 = new Chopstick("4");
		Chopstick chopstick5 = new Chopstick("5");
		
		new Philosopher("philosopher1", chopstick1, chopstick2).start();
		new Philosopher("philosopher2", chopstick2, chopstick3).start();
		new Philosopher("philosopher3", chopstick3, chopstick4).start();
		new Philosopher("philosopher4", chopstick4, chopstick5).start();
		new Philosopher("philosopher5", chopstick5, chopstick1).start();
		
		
	}

}

class Philosopher extends Thread {
	private static final Logger logger = LoggerFactory.getLogger(Philosopher.class);
	private Chopstick left;
	private Chopstick right;
	
	public Philosopher(String name, Chopstick left, Chopstick right) {
		super(name);
		this.left = left;
		this.right = right;
	}
	
	@Override
	public void run() {
		while(true) {
			if (left.tryLock()) {
				try {
					if (right.tryLock()) {
						try {
							eat();
						} finally {
							right.unlock();
						}
					} 
				} finally {
					left.unlock();
				}
			}
		}
	}

	private void eat() {
		logger.info("eating...");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
class Chopstick extends ReentrantLock{
	private String name;

	public Chopstick(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Chopstick []";
	}
}